<template>
	<view class="container">
		<!-- 页面导航栏 -->
		<page-navbar title="商品列表"></page-navbar>

		<!-- 搜索框 -->
		<view class="search-section">
			<view class="search-box">
				<uni-icons type="search" size="18" color="#999" @click='onSearchInput'></uni-icons>
				<input class="search-input" placeholder="搜索商品名称" v-model="searchKeyword" @input="onSearchInput" />
				<view class="search-clear" v-if="searchKeyword" @click="clearSearch" @confirm="onSearchInput">
					<uni-icons type="clear" size="16" color="#999"></uni-icons>
				</view>
			</view>
		</view>

		<!-- 类型筛选标签 -->
		<view class="filter-section">
			<scroll-view class="filter-tabs" scroll-x="true" show-scrollbar="false">
				<view class="filter-list">
					<view class="filter-item" :class="{ active: currentType === item.value }"
						v-for="(item, index) in filterTypes" :key="index" @click="switchType(item.value)">
						{{ item.name }}
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 商品列表 -->
		<scroll-view class="commodity-scroll" scroll-y="true" @scrolltolower="loadMore" :refresher-enabled="true"
			:refresher-triggered="refreshing" @refresherrefresh="onRefresh">
			<view class="commodity-list">
				<view class="commodity-item" v-for="(item, index) in commodityList" :key="index"
					@click="handleCommodity(item)">
					<view class="commodity-image-wrapper">
						<image class="commodity-image" :src="common.defaultImg(item.commodity_images)" mode="aspectFill"
							@error="handleImageError">
						</image>
						<view class="commodity-badge">{{ item.tag ? item.tag : '推荐' }}</view>
					</view>
					<view class="commodity-content">
						<text class="commodity-name">{{ item.commodity_name }}</text>
						<view class="commodity-type-box">
							<text class="commodity-type">{{ item.type?.name }}</text>
						</view>
						<view class="commodity-price-box">
							<view class="price-group">
								<text class="commodity-price">¥{{ filterPrice(item.sale_price, item.discount) }}</text>
								<text class="original-price" v-if="item.discount">¥{{ item.sale_price }}</text>

							</view>
						</view>
						<view class="commodity-info-box">
							<text class="discount-tag" v-if="item.discount && item.discount != 1">{{ item.discount * 10	 }}折</text>
							<text class="commodity-sold">已售{{ item.sales_quantity }}件</text>
						</view>
						<view class="promotion-box" v-if="item.full_amount">
							<text class="promotion-tag">满减</text>
							<text class="promotion-text">{{ `满${item.full_amount}减${item.full_reduction}` }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多状态 -->
			<view class="load-more-status" v-if="commodityList.length > 0">
				<view v-if="loading" class="loading">
					<uni-icons type="spinner-cycle" size="16" color="#999"></uni-icons>
					<text class="loading-text">加载中...</text>
				</view>
				<view v-else-if="noMore" class="no-more">
					<text>没有更多商品了</text>
				</view>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="commodityList.length === 0 && !loading">
				<image class="empty-image" src="/static/images/empty.svg" mode="aspectFit"></image>
				<text class="empty-text">{{ searchKeyword ? '未找到相关商品' : '暂无商品信息' }}</text>
				<text class="empty-desc">{{ searchKeyword ? '换个关键词试试吧' : '商品信息正在准备中，敬请期待...' }}</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { onLoad, onShow, onReachBottom } from '@dcloudio/uni-app';
import PageNavbar from '@/components/page-navbar/page-navbar.vue';
import SvgIcon from '@/components/svg-icon/svg-icon.vue';
import api from "@/api"
import common from '@/utils/common.js';

// 搜索关键词
const searchKeyword = ref('');
const searchTimer = ref(null);

// 筛选类型
const currentType = ref('');
const filterTypes = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(20);
const loading = ref(false);
const refreshing = ref(false); // 下拉刷新状态
const noMore = ref(false); // 是否没有更多数据
const total = ref(0); // 总数据量


// 商品列表数据 - 更新为与首页一致
const commodityList = ref([]);

onMounted(() => {
	getData()
})

const getData = () => {
	api.commerceApi.typeList({ page: 1, pageSize: 100 }).then((res) => {
		let arr = res.list.map(item => {
			return {
				name: item.name,
				value: item.id
			}
		})
		filterTypes.value = [{ name: '全部', value: '' }, ...arr]
		getList()
	});
}
// 获取商品列表
const getList = () => {
	api.commerceApi.list({
		page: currentPage.value,
		pageSize: pageSize.value,
		commodity_category: currentType.value,
		commodity_name: searchKeyword.value,
		loding: true
	}).then((res) => {
		total.value = res.total;
		if (currentPage.value == 1) {
			commodityList.value = res.list;
		} else {
			commodityList.value = [...commodityList.value, ...res.list];
		}
		loading.value = false;
		if (commodityList.value.length >= total.value) {
			noMore.value = true;
		} else {
			noMore.value = false;
		}
		refreshing.value = false;
		console.log('商品列表原始数据:', commodityList.value);
	});
}

// 售价
const filterPrice = (sale_price, discount) => {
	if (discount) {
		return (sale_price * discount).toFixed(2);
	} else {
		return sale_price;
	}
};

// 搜索输入处理
const onSearchInput = () => {
	// 防抖处理
	if (searchTimer.value) {
		clearTimeout(searchTimer.value);
	}
	searchTimer.value = setTimeout(() => {
		// 这里可以调用搜索API
		currentPage.value = 1;
		commodityList.value = []
		getList()
	}, 500);
};

// 清除搜索
const clearSearch = () => {
	searchKeyword.value = '';
	currentPage.value = 1;
	commodityList.value = []
	getList()
};

// 切换类型
const switchType = (type) => {
	currentType.value = type;
	currentPage.value = 1;
	commodityList.value = []
	getList()
};

// 下拉刷新
const onRefresh = async () => {
	refreshing.value = true;
	currentPage.value = 1;
	noMore.value = false;
	getList();
};

// 触底加载更多
const loadMore = async () => {
	if (loading.value || noMore.value) return;
	loading.value = true;
	currentPage.value++;
	getList();
};

// 商品点击
const handleCommodity = (item) => {
	uni.navigateTo({
		url: `/pages/commerce/detail?id=${item.id}`
	});
};

// 图片加载错误处理
const handleImageError = (event) => {
	console.log('图片加载失败，使用默认图片');
	event.target.src = '/static/images/default-commodity.svg';
};

</script>

<style lang="scss" scoped>
.container {
	background-color: #f2f1f6;
	height: 100vh;
	width: 100vw;
	display: flex;
	flex-direction: column;
	box-sizing: border-box;
}

.search-section {
	padding: 12rpx 24rpx;
	background: white;

	.search-box {
		display: flex;
		align-items: center;
		background: #f5f5f5;
		border-radius: 25rpx;
		padding: 12rpx 24rpx;
		box-sizing: border-box;
		height: 80rpx;
		gap: 20rpx;

		.search-input {
			flex: 1;
			font-size: 28rpx;
			line-height: 28rpx;
			color: #333;
			height: 100%;

			&::placeholder {
				color: #999;
			}
		}

		.search-clear {
			padding: 10rpx;
		}
	}
}

.filter-section {
	background: white;
	padding: 12rpx 0;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	box-sizing: border-box;

	.filter-tabs {
		white-space: nowrap;

		/* 隐藏滚动条 */
		/* #ifdef H5 */
		&::-webkit-scrollbar {
			display: none;
			width: 0;
			height: 0;
		}

		scrollbar-width: none;
		-ms-overflow-style: none;
		/* #endif */

		/* #ifdef MP-WEIXIN */
		::-webkit-scrollbar {
			display: none;
		}

		/* #endif */

		.filter-list {
			display: flex;
			padding: 15rpx 20rpx;
			box-sizing: border-box;
			gap: 20rpx;

			.filter-item {
				flex-shrink: 0;
				padding: 12rpx 28rpx;
				font-size: 26rpx;
				color: #666;
				background: #f3f4f5;
				border-radius: 50rpx;
				border: 2rpx solid transparent;
				transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
				font-weight: 500;
				position: relative;
				overflow: hidden;
				letter-spacing: 2rpx;

				&::before {
					content: '';
					position: absolute;
					top: 0;
					left: -100%;
					width: 100%;
					height: 100%;
					background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
					transition: left 0.5s;
				}

				&.active {
					color: white;
					background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
					border-color: #56ab2f;
					box-shadow: 0 6rpx 20rpx rgba(86, 171, 47, 0.4);

					&::before {
						left: 100%;
					}
				}

				&:not(.active):active {
					transform: scale(0.96);
					background: #e9ecef;
				}
			}
		}
	}
}

.commodity-scroll {
	flex: 1;
	height: 0; // 关键：让scroll-view占据剩余空间
}

.commodity-list {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 20rpx;
	padding: 20rpx;
}

.commodity-item {
	border-radius: 16rpx;
	overflow: hidden;
	background: white;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	transition: all 0.3s ease;

	&:active {
		transform: translateY(-4rpx);
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
	}

	.commodity-image-wrapper {
		position: relative;

		.commodity-image {
			width: 100%;
			height: 200rpx;
		}

		.commodity-badge {
			position: absolute;
			top: 10rpx;
			right: 10rpx;
			background: linear-gradient(135deg, #FF6B6B, #FF8E8E);
			color: white;
			font-size: 20rpx;
			padding: 4rpx 12rpx;
			border-radius: 12rpx;
			font-weight: bold;
		}


	}

	.commodity-content {
		padding: 0 20rpx 20rpx;

		.commodity-name {
			display: block;
			font-size: 28rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 8rpx;
			//限制显示一行
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		.commodity-type-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.commodity-type {
			font-size: 22rpx;
			color: #666;
			padding: 4rpx 12rpx;
			background: rgba(102, 102, 102, 0.1);
			border-radius: 8rpx;
			margin-bottom: 12rpx;
			display: inline-block;
		}

		.commodity-price-box {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.price-group {
				display: flex;
				align-items: center;
				gap: 8rpx;

				.commodity-price {
					font-size: 32rpx;
					color: #FF6B6B;
					font-weight: bold;
				}

				.original-price {
					font-size: 24rpx;
					color: #999;
					text-decoration: line-through;
				}
			}
		}

		.commodity-info-box {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.discount-tag {
				font-size: 20rpx;
				color: #FF6B6B;
				background: rgba(255, 107, 107, 0.1);
				padding: 2rpx 8rpx;
				border-radius: 6rpx;
			}

			.commodity-sold {
				font-size: 22rpx;
				color: #999;
			}
		}

		.promotion-box {
			margin-top: 8rpx;
			display: flex;
			align-items: center;
			gap: 8rpx;

			.promotion-tag {
				font-size: 20rpx;
				color: #FF6B6B;
				background: rgba(255, 107, 107, 0.1);
				padding: 2rpx 8rpx;
				border-radius: 6rpx;
			}

			.promotion-text {
				font-size: 20rpx;
				color: #666;
			}
		}
	}
}

.load-more-status {
	padding: 30rpx 20rpx;
	text-align: center;

	.loading {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
		color: #999;

		.loading-text {
			font-size: 24rpx;
		}
	}

	.no-more {
		color: #999;
		font-size: 24rpx;
	}
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 40rpx;

	.empty-image {
		width: 240rpx;
		height: 240rpx;
		margin-bottom: 40rpx;
	}

	.empty-text {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 16rpx;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #999;
		text-align: center;
	}
}
</style>
